package com.chrelyonly.util.wx;

import com.chrelyonly.util.myRes.AjaxJson;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.service.WxOAuth2Service;
import me.chanjar.weixin.mp.api.impl.WxMpOAuth2ServiceImpl;

import java.net.MalformedURLException;
import java.net.URISyntaxException;

import static java.lang.System.out;

/**
 * @author chrelyonly
 * 微信网页授权工具
 */
@Slf4j
public class WxWebOauthUtil {


    /**
     * 初始化授权
     */
    public static WxOAuth2Service wxoAuth2Service() {
//       设置授权参数
        return new WxMpOAuth2ServiceImpl(WxInIt.wxMpService());
    }

    /**
     * 微信授权地址  获取code
     */
    public static AjaxJson wxGetCode(HttpServletRequest request) throws MalformedURLException, URISyntaxException {
        // 获取请求行的相关信息
        String serverName = request.getServerName();
        final WxOAuth2Service wxAuth2Service = wxoAuth2Service();
//      拼接授权地址
//        1.回调地址
//        2.授权类型
//        3.授权后携带参数
        final String url = wxAuth2Service.buildAuthorizationUrl(request.getScheme() + "://" + serverName + "/wxGetUserInfo", WxConsts.OAuth2Scope.SNSAPI_USERINFO, serverName + "/wxGetUserInfo");
        log.info("授权地址:" + url);
        return AjaxJson.success().put("url", url);
    }

    /**
     * @param code     换取openid
     * @param state    携带参数
     */
    public static AjaxJson wxGetOpenId(String code, String state, HttpServletResponse response) throws WxErrorException {
//        初始化参数
        final WxOAuth2Service wxAuth2Service = wxoAuth2Service();
//       获取 AccessToken
        final WxOAuth2AccessToken accessToken = wxAuth2Service.getAccessToken(code);
        out.println(accessToken);
//        获取 用户信息
        final WxOAuth2UserInfo userInfo = wxAuth2Service.getUserInfo(accessToken, "");
        return AjaxJson.success().put("wxUserInfo", userInfo);
    }
}
